//
//  DLSearchView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/13.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLSearchView.h"
#import "DLInfoSearchModel.h"
@interface DLSearchView()<UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation DLSearchView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.dataSource = [NSMutableArray array];
        [self layoutSubControls];
        self.backgroundColor = [UIColor whiteColor];
        self.layer.cornerRadius = self.height / 2;
        self.clipsToBounds = YES;
    }
    return self;
}

- (void) searchNewsWithKeyword:(NSString *)keyword {
    
    if(self.searchBlock) {
        self.searchBlock(keyword);
    }
}

- (void) layoutSubControls {
    
    UITextField *searchTF = [UITextField new];
    searchTF.delegate = self;
    searchTF.frame = self.bounds;
    [self addSubview:searchTF];
    self.searchTF = searchTF;
    
    UIView *leftBgView = [UIView new];
    leftBgView.frame = CGRectMake(0, 0, 30, 30);
    
    UIImageView *imageV = [UIImageView new];
    imageV.frame = CGRectMake(7, 7, 16, 16);
    imageV.image = [UIImage imageNamed:@"search_gray"];
    [leftBgView addSubview:imageV];
    
    searchTF.leftView = leftBgView;
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    
    searchTF.font = kSystemFont(13);
    searchTF.placeholder = @"请输入您要搜索的关键字";
    searchTF.borderStyle = UITextBorderStyleNone;
    searchTF.keyboardType = UIKeyboardTypeDefault;
    searchTF.returnKeyType = UIReturnKeySearch;
    searchTF.clearButtonMode = UITextFieldViewModeAlways;
    
    searchTF.backgroundColor = [UIColor whiteColor];
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
    
    NSString *temp = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([temp length] == 0) {
        NSLog(@"全是空格");
        return NO;
    }
    NSString *newString = [self removeSpaceAndNewline:textField.text];
    NSLog(@"去除空格和换行之后的字符串是：%@", newString);
    [self searchNewsWithKeyword:newString];
    return YES;
}
- (NSString *)removeSpaceAndNewline:(NSString *)str{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
